package scatter.file.rest.cloudstorage.service.impl;


import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import scatter.common.rest.tools.InterfaceTool;
import scatter.common.rest.tools.IoStreamTool;
import scatter.common.rest.tools.PathTool;
import scatter.file.rest.cloudstorage.config.impl.LocalStorageConfig;

import java.io.*;

import static scatter.file.rest.cloudstorage.controller.CloudStorageController.API_DOWNLOAD_PREFIX;

/**
 * Created by yangwei
 * Created at 2019/3/14 11:45
 */
@Slf4j
@Service
public class LocalStorageServiceImpl extends AbstractCloudStorageService implements InterfaceTool {
    @Autowired
    private LocalStorageConfig config;

    @Override
    public boolean support(String type) {
        return isEqual(config.uploadType(),type);
    }


    @Override
    public String upload(byte[] data, String filepath) {
        return upload(new ByteArrayInputStream(data),filepath);
    }

    @Override
    public String uploadSuffix(byte[] data,String prefixPath, String suffix) {
        return upload(new ByteArrayInputStream(data),newPath(PathTool.concat(prefixPath),suffix));
    }

    @Override
    public String upload(InputStream inputStream, String filepath) {
        String concat = PathTool.concat(config.getLocation(), config.getPrefix(), filepath);
        FileUtil.writeFromStream(inputStream, concat);
        log.info("本地文件存储位置={}",FileUtil.file(concat).getAbsolutePath());
        return getResult(config.getDomain(),PathTool.concat(API_DOWNLOAD_PREFIX,config.getPrefix()) ,filepath,config.uploadType());
    }

    @Override
    public String uploadSuffix(InputStream inputStream,String prefixPath, String suffix) {
        return upload(inputStream,newPath(PathTool.concat(prefixPath),suffix));
    }

    @Override
    public byte[] download(String objectName) {
        try {
            return IoStreamTool.inputStreamToByteArray(new FileInputStream(new File(PathTool.concat(this.config.getLocation(), objectName))));
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(),e);
        }
    }

    @Override
    public boolean delete(String objectName) {
        boolean r  = FileUtil.del(PathTool.concat(this.config.getLocation()  ,objectName));
        return r;
    }
}
